package com.feige.web.result;

import com.feige.constant.Constants;
import com.feige.utils.exception.BaseException;
import com.feige.utils.exception.BusinessException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * @author feige
 */
@ApiModel(value = "返回基类")
@Data
public abstract class BaseResult implements Serializable {


    private static final long serialVersionUID = -8620629676789739106L;

    @ApiModelProperty(
            value = "状态",
            example = "0"
    )
    protected int status = Constants.SUCCESS_STATUS;


    @ApiModelProperty(
            value = "错误码",
            example = "0000"
    )
    protected String code = Constants.SUCCESS_CODE;

    @ApiModelProperty(
            value = "提示消息",
            example = "成功"
    )
    protected String msg = Constants.SUCCESS_MSG;

    public BaseResult setSuccess(){
        this.setStatus(Constants.SUCCESS_STATUS);
        this.setCode(Constants.SUCCESS_CODE);
        this.setMsg(Constants.SUCCESS_MSG);
        return this;
    }

    public BaseResult setFailure(){
        this.setStatus(Constants.FAILURE_STATUS);
        this.setCode(Constants.FAILURE_CODE);
        this.setMsg(Constants.FAILURE_MSG);
        return this;
    }

    public BaseResult setNoAuth(){
        this.setStatus(Constants.FAILURE_STATUS);
        this.setCode(Constants.NO_AUTH_CODE);
        this.setMsg(Constants.NO_AUTH_MSG);
        return this;
    }

    public BaseResult setException(Exception e){
        if (e == null) {
            return setFailure();
        }
        this.setMsg(e.getMessage());
        this.setStatus(Constants.FAILURE_STATUS);
        if (e instanceof BusinessException){
            BaseException be = (BusinessException) e;
            this.setCode(be.getCode());
        }else {
            this.setCode(Constants.FAILURE_CODE);
        }
        return this;
    }

}
